package com.polaris.live.ui.login.verify

import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.EditText
import androidx.activity.result.contract.ActivityResultContracts
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.basic.ActivityLauncher
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.resp.Ext
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.ActivityInputPasswordBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.PwsErrorInputTimeDialog
import com.polaris.live.dialog.PwsErrorProhibitLoginDialog
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.translation.R.string
import com.polaris.live.ui.main.activity.MainActivity
import com.polaris.live.utils.UserUtils
import com.polaris.live.viewmodel.VerifyViewModel

/**
 * InputPasswordActivity
 *
 * @author Created by 半仙 on 2023/9/4/004 14:33
 */
class InputPasswordActivity : BaseVbActivity<VerifyViewModel, ActivityInputPasswordBinding>() {

    private var mIsShowLook = false // 判断密码是否可见
    private var mAreaCode: String? = ""
    private var mPhoneNumber: String? = ""
    private var mGmail: String? = ""
    private val mLauncher = ActivityLauncher(this, this)

    private var mIsPopupBoard = false //判断是否弹出软件盘了

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
    }

    override fun initView(savedInstanceState: Bundle?) {
        initView()
        initObserve()
    }


    private fun initView() {
        mAreaCode = intent.getStringExtra("areaCode")
        mPhoneNumber = intent.getStringExtra("phoneNumber")
        mGmail = intent.getStringExtra("gmail")

        mBinding.passwordEdit.requestFocus()

        mBinding.passwordEdit.inputType =
            InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

        mBinding.passwordEdit.addTextChangedListener(object : TextWatcherAdapter() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val toString = s?.toString()
                val trimmedStr = toString?.replace("\\s+".toRegex(), "")  // 去掉所有空格
                val size = trimmedStr?.length ?: 0
                if (size < 6) {
                    mBinding.goLogin.alpha = AppConst.NOTCLICK
                } else {
                    mBinding.goLogin.alpha = 1.0f
                }
            }
        })

        mBinding.goLogin.setOnSingleClickListener {
            val size = mBinding.passwordEdit.text.length
            if (size >= 6) {
                if (isGmailLogin()) {
                    mViewModel.loginGmailByPassword(
                        mGmail ?: "",
                        mBinding.passwordEdit.text.toString(),
                        AppConst.UserPwdType.PASSWORD
                    )
                } else {
                    mViewModel.loginPhoneByPassword(
                        mAreaCode ?: "",
                        mPhoneNumber ?: "",
                        mBinding.passwordEdit.text.toString(),
                        AppConst.UserPwdType.PASSWORD
                    )
                }
            } else {
                ToastGravity.showGravity(string.password_min_limit)
            }
        }

        mBinding.passwordVisible.setOnClickListener {
            if (mIsShowLook) {
                mIsShowLook = false
                // 设置为不可见密码模式
                mBinding.passwordEdit.transformationMethod = PasswordTransformationMethod.getInstance()
                mBinding.passwordVisible.setImageResource(R.drawable.not_visible)

            } else {
                mIsShowLook = true
                // 设置为可见密码模式
                mBinding.passwordEdit.transformationMethod = HideReturnsTransformationMethod.getInstance()
                mBinding.passwordVisible.setImageResource(R.drawable.ok_visible)
            }
            val size = mBinding.passwordEdit.text.length
            mBinding.passwordEdit.setSelection(size)
        }

        mBinding.forsakePassword.text = SpanUtils.with(mBinding.forsakePassword)
            .append(StringUtils.getString(string.forsake_password)).setUnderline().create()

        mBinding.forsakePassword.setOnSingleClickListener {
            val intent = Intent(this, SetPasswordActivity::class.java)
            intent.putExtra("isLogin", true)
            intent.putExtra("isFirstSet", false)
            intent.putExtra("phoneNumber", mPhoneNumber)
            intent.putExtra("areaCode", mAreaCode)
            intent.putExtra("gmail", mGmail)
            startActivity.launch(intent)
        }

        setEditTextInputSpace(mBinding.passwordEdit)
    }

    private fun isGmailLogin(): Boolean {
        return !mGmail.isNullOrEmpty()
    }

    /**
     * 禁止EditText输入空格和换行符
     *
     * @param editText EditText输入框
     */
    private fun setEditTextInputSpace(editText: EditText) {
        val filter = InputFilter { source, start, end, dest, dstart, dend ->
            if (source == " " || source.toString().contentEquals("\n")) {
                ""
            } else {
                null
            }
        }
        editText.filters = arrayOf(filter)
    }

    private fun initObserve() {
        mViewModel.loginPwsRespLiveData.observe(this) { resultState ->
            parseState(resultState, {
                //登录成功
                saveSuccessPhoneNumber()
                UserUtils.loginSuccess(it)
                startActivity(Intent(this, MainActivity::class.java))
                finish()
            }, {
                when (it.errCode) {
                    CommonConst.ErrorCode.LOGIN_PASSWORD_ERROR -> {
                        val ext = JsonUtils.fromJson<Ext>(JsonUtils.toJson(it.ext))
                        ext?.remainTime?.let { remainTime ->
                            val builder = XPopup.Builder(this)
                                .dismissOnTouchOutside(false)
                                .dismissOnBackPressed(false)
                                .isDestroyOnDismiss(true)
                            if (remainTime > 0) {
                                builder.asCustom(PwsErrorInputTimeDialog(this, remainTime))
                                    .show()
                            }
                        }
                    }

                    CommonConst.ErrorCode.LOGIN_PASSWORD_ERROR_UPPER_LIMIT -> {
                        XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .isDestroyOnDismiss(true)
                            .asCustom(
                                PwsErrorProhibitLoginDialog(
                                    this,
                                    mAreaCode ?: "",
                                    mPhoneNumber ?: "",
                                    mGmail ?: "",
                                    mLauncher
                                )
                            ).show()
                    }

                    CommonConst.ErrorCode.SEAL_ACCOUNT, CommonConst.ErrorCode.SEAL_ACCOUNT_LOGIN, CommonConst.ErrorCode.SEAL_ACCOUNT_STOP -> {
                        GlobalDialogManager.showSealAccountDialog(
                            this,
                            JsonUtils.toJson(it.ext)
                        )
                    }

                    else -> {
                        ToastGravity.showGravity(it.errorMsg)
                    }
                }
            })
        }
    }

    private fun saveSuccessPhoneNumber() {
        val areaCode = mAreaCode
        val phoneNumber = mPhoneNumber
        if (areaCode != null && phoneNumber != null) {
            CacheUtil.saveLastAreaCodeAndPhoneNumber(areaCode, phoneNumber)
        }
        val gmail = mGmail
        if (gmail != null) {
            CacheUtil.saveLastGmail(gmail)
        }
    }

    private val startActivity =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            //此处是跳转的result回调方法
            if (it.data != null && it.resultCode == RESULT_OK) {
                finish()
            }
        }
}